//
//  EditScheduleViewController.m
//  project
//
//  Created by 圆圆陈 on 2018/1/3.
//  Copyright © 2018年 黄建华. All rights reserved.
//

#import "EditScheduleViewController.h"
#import <UserNotifications/UserNotifications.h>
@interface EditScheduleViewController ()
@property(nonatomic,strong)UITextField *textField;
@property(nonatomic,strong)UILabel *timeLabel;
@property(nonatomic,strong)UIDatePicker *datePciker;
@end

@implementation EditScheduleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *StateView = [[UIView alloc] init];
    StateView.frame = CGRectMake(0, 0, kSCREEN_WIDTH, 20);
    StateView.backgroundColor = BBIGSTATECOLOR;
    [self.view addSubview:StateView];
    
    UIView *naView = [[UIView alloc] init];
    naView.frame = CGRectMake(0, 20+FitSimpleIpx(0, 20), kSCREEN_WIDTH, 44);
    naView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:naView];
    
    UILabel *lable=[[UILabel alloc]initWithFrame:CGRectMake(0, 20+FitSimpleIpx(0, 20),screenWidth, 44)];
    lable.textColor= UIColorHEX(0x161616);
    lable.font= SNFONTMEDIUM(17);
    lable.textAlignment = NSTextAlignmentCenter;
    lable.text = HHH_Text(@"编辑日程");
    
    [self.view addSubview:lable];
    
    UIButton *leftButton = [[UIButton alloc] init];
    leftButton.frame = CGRectMake(5, 20+FitSimpleIpx(0, 20), 44, 44);
    [leftButton setImageNormal:@"进入"];
    [leftButton addTarget:self action:@selector(leftbuttonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftButton];
    
    UIButton *rightButton = [[UIButton alloc] init];
    rightButton.frame = CGRectMake(HHHWIDTH-80-10, 20+FitSimpleIpx(0, 20), 80, 44);
    [rightButton setTitleNormal:HHH_Text(@"保存")];
    rightButton.titleLabel.font = SNFONTMEDIUM(16);
    rightButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [rightButton setTitleColorNormal:UIColorHEX(0xFF9500)];
    [rightButton addTarget:self action:@selector(rightButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rightButton];
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, naView.bottom+10, HHHWIDTH,50)];
    bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgView];
    
    _textField = [[UITextField alloc]initWithFrame:CGRectMake(15, naView.bottom+10, HHHWIDTH-30,50)];
    _textField.placeholder = HHH_Text(@"提醒内容");
    _textField.textColor = SNCOLORBLACK;
    [self.view addSubview:_textField];
    _textField.backgroundColor = [UIColor whiteColor];
    
    UILabel *line1 = [[UILabel alloc]initWithFrame:CGRectMake(0, _textField.bottom, HHHWIDTH, 2)];
    line1.backgroundColor = UIColorHEX(0xd9d9d9);
//    [self.view addSubview:line1];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(FitW(15), line1.bottom, HHHWIDTH/2-FitW(15),60)];
    label.text = HHH_Text(@"时间");
    label.textAlignment = NSTextAlignmentLeft;
    label.textColor = UIColorHEX(0x161616);
    [self.view addSubview:label];
    
    _timeLabel =[[UILabel alloc]initWithFrame:CGRectMake(HHHWIDTH/2, line1.bottom, HHHWIDTH/2-FitW(15), 60)];
    _timeLabel.textAlignment = NSTextAlignmentRight;
    _timeLabel.textColor = UIColorHEX(0x161616);
    _timeLabel.font = SNFONTMEDIUM(17);
    [self.view addSubview:_timeLabel];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"]; // 这里是用大写的 H
    NSString* dateStr = [formatter stringFromDate:[NSDate date]];
    NSDate *date = [formatter dateFromString:dateStr];
    _timeLabel.text = dateStr;
    
    _datePciker = [[UIDatePicker alloc]init];
    _datePciker.frame = CGRectMake(15, _timeLabel.bottom, HHHWIDTH-30, 230);
    _datePciker.datePickerMode = UIDatePickerModeDateAndTime;
    _datePciker.locale = [NSLocale currentLocale];
    [_datePciker setDate:date];
    [_datePciker setMinimumDate:date];
    [_datePciker addTarget:self action:@selector(valueChange) forControlEvents:UIControlEventValueChanged];
    [_datePciker setValue:SNCOLORBLACK forKey:@"textColor"]; //设置字体颜色
    [self.view addSubview:_datePciker];
    
    _datePciker.layer.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0].CGColor;
    _datePciker.layer.cornerRadius = 6;
    
    self.view.backgroundColor = UIColorHEX(0xf0f2f5);
    
    if (_type==1) {
        _textField.text = _model.info;
        _timeLabel.text = [NSString stringWithFormat:@"%ld-%02ld-%02ld %02ld:%02ld",_model.year,_model.month,_model.day,_model.hours,_model.mins];
        _datePciker.date =[formatter dateFromString:_timeLabel.text];
    }
    
//    SNShadowView *shadowLine = [[SNShadowView alloc] init];
//    shadowLine.frame = SNFRAME(0,20+FitSimpleIpx(0, 20) + 44, HHHWIDTH, 0);
//    [shadowLine showWithType:1];
//    [self.view addSubview:shadowLine];
    UIImageView *shadowLine = [[UIImageView alloc] init];
    shadowLine.frame = SNFRAME(0, 20+FitSimpleIpx(0, 20) + 44 -2, HHHWIDTH, 2);
    shadowLine.image = [UIImage image:@"lineImage"];
//    [self.view addSubview:shadowLine];
}
-(void)setModel:(SNcalendarModel *)model{
    _model = model;
}
- (void)leftbuttonClick
{
    SN_USER = [SNUserInfoModel getUserInfoFromDBWithUserID:[KK_LastUser getObjectValue]];
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)rightButtonClick{
    if (SN_USER.showCalendarArray.count==5) {
        SHOWMBProgressHUD(nil,HHH_Text(@"最多可以设置5个日程"), nil, NO, 1);
        return;
    }
    if ([_textField.text isEqualToString:@""]) {
        SHOWMBProgressHUD(nil,HHH_Text(@"提醒内容不能为空"), nil, NO, 1);
        return;
    }
    NSDate *date =_datePciker.date;
    _model.open = YES;
    _model.year =date.year;
    _model.month = date.month;
    _model.day = date.day;
    _model.hours = date.hour;
    _model.mins = date.minute;
    _model.info = _textField.text;
    _model.date = date;
    if (_type==0) {
        _model.orderIndex = SN_USER.showCalendarArray.count;
        [SN_USER.showCalendarArray addObject:_model];
    }else{
        [SN_USER.showCalendarArray replaceObjectAtIndex:_model.orderIndex withObject:_model];
    }
    //将日程按时间排序
    [SN_USER.showCalendarArray sortUsingComparator:^NSComparisonResult(SNcalendarModel* obj1, SNcalendarModel* obj2) {
        return [obj1.date compare:obj2.date];
    }];
    //重排序后将日程的orderIndex重新按在数组中的顺序赋值
    NSMutableArray *arr = [NSMutableArray array];
    for (int i=0; i<SN_USER.showCalendarArray.count; i++) {
        SNcalendarModel* model = SN_USER.showCalendarArray[i];
        model.orderIndex = i;
        [arr addObject:model];
    }
    SN_USER.showCalendarArray = arr.mutableCopy;
    for (int i=0; i<SN_USER.showCalendarArray.count; i++) {
        [SN_USER.calendarArray replaceObjectAtIndex:i withObject:SN_USER.showCalendarArray[i]];
    }
    [SN_USER updateToDB];
    if (IOS10_OR_LATER) {//ios 10
        if (_model.open) {
            UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];

            UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];

            content.title = [NSString localizedUserNotificationStringForKey:SN_Text(@"日程提醒") arguments:nil];

            content.body = [NSString localizedUserNotificationStringForKey:_model.info arguments:nil];

            content.sound = [UNNotificationSound defaultSound];
            
            content.badge = [NSNumber numberWithInteger:_model.orderIndex+1];
            
            NSCalendar *gregorian = [NSCalendar currentCalendar];

            NSDate* dt = _datePciker.date;
            unsigned unitFlags = NSCalendarUnitYear|NSCalendarUnitMonth|
            NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
            
            NSDateComponents *components = [gregorian components:unitFlags fromDate:dt];
           
            UNCalendarNotificationTrigger* trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:NO];
            NSString *identifier = [NSString stringWithFormat:@"Schedule%ld",_model.orderIndex];
            UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];

            [center addNotificationRequest:request withCompletionHandler:nil];
        }
    }else{
        if (_model.open) {
            UILocalNotification *notification = [[UILocalNotification alloc] init];
            notification.timeZone = [NSTimeZone localTimeZone];
            notification.fireDate = _datePciker.date;
            notification.repeatCalendar=[NSCalendar currentCalendar];
            notification.alertBody = _model.info;
            notification.alertAction = @"打开应用";
            notification.soundName = UILocalNotificationDefaultSoundName;
            notification.applicationIconBadgeNumber = _model.orderIndex+1;
            [[UIApplication sharedApplication] scheduleLocalNotification:notification];
        }
    }
       
    [SN_EveryDayModelHelp startSetCalendar];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)valueChange{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"]; // 这里是用大写的 H
    _timeLabel.text = [formatter stringFromDate:_datePciker.date];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
